import axios from 'axios'
import { removeToken, getToken } from './storage'
import router from '@/router'

import { Toast } from 'vant'
const request = axios.create({
  baseURL: 'http://localhost:1337/',
  // baseURL: 'http://hmmm.zllhyy.cn/',
  timeout: 10000
})

// 添加请求拦截器
request.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    if (config.flag) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    if (response.data.code === 401) {
      Toast.fail('登录异常，请重新登录')
      router.push('/login')
      removeToken()
      return
    }
    return response.data
  },
  function (error) {
    return Promise.reject(error)
  }
)
export default request
